package com.lin.wx.official.account.manager;


import com.lin.wx.official.account.common.WxMessageEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author linjiang
 * @date 2024/6/22
 * @fn
 */
@Slf4j
@Component
public class WxMessageHelper implements InitializingBean {

    @Resource
    List<MessageHandler> messageHandlerList;

    Map<WxMessageEnum, MessageHandler> messageServiceMap = new HashMap<>();

    /**
     * 构建微信消息处理器
     *
     * @return
     */
    public MessageHandler get(String msgType) {
        WxMessageEnum messageEnum = WxMessageEnum.getByMsgType(msgType);
        MessageHandler handler = messageServiceMap.get(messageEnum);
        if (Objects.nonNull(handler)) {
            return handler;
        } else {
            log.info(String.format("系统未开发此消息类型【%s】的接口", msgType));
            return messageServiceMap.get(WxMessageEnum.DEFAULT);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        for (MessageHandler handler : messageHandlerList) {
            messageServiceMap.put(handler.getMsgType(), handler);
        }
    }
}
